package com.own.business.resource.core.util;

import com.own.business.resource.core.base.AbstractObjectStoreUtil;
import com.own.business.resource.core.em.ResourceUploadMethodEnum;
import com.own.business.resource.core.model.base.BaseUploadModel;
import com.own.business.resource.core.property.ResourceSourceProperty;
import com.own.component.common.util.FileUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.util.List;

/**
 * LocalObjectStoreUtil
 *
 * @author chenxueli
 * @date 2023-07-07 14:30:34
 */
@Slf4j
public class LocalObjectStoreUtil extends AbstractObjectStoreUtil {

    public LocalObjectStoreUtil() {
        super();
        log.warn("本地文件上传方式可作为开发使用，测试、生产环境推荐更加稳定的minio分布式存储方案");
        var property = new ResourceSourceProperty();
        property.setClassName(ResourceUploadMethodEnum.LOCAL.getClassName());
        property.setPosition("/");
        setConfigAndCheck("default", property);
    }

    /**
     * 上传单个文件
     *
     * @param file 文件信息
     * @return 文件存储对象信息
     */
    @Override
    public BaseUploadModel uploadFile(BaseUploadModel file) {
        // 将文件写入到本地
        FileUtil.write(FileUtil.getUploadFolder() + file.getFolder(), file.getFileName(), file.getInputStream());
        file.success();
        return file;
    }

    /**
     * 上传多个文件
     *
     * @param fileList 文件信息列表
     * @return 文件存储对象信息列表
     */
    @Override
    public List<BaseUploadModel> uploadFile(List<BaseUploadModel> fileList) {
        var folder = FileUtil.getUploadFolder();
        fileList.parallelStream().forEach(file -> {
            FileUtil.write(folder + file.getFolder(), file.getFileName(), file.getInputStream());
            file.success();
        });
        return fileList;
    }

    /**
     * 默认的上传路径
     *
     * @return 上传路径
     */
    @Override
    public String uploadPath() {
        return FileUtil.FILE_ROOT_NAME + File.separator + FileUtil.FILE_UPLOAD_NAME;
    }

}
